package com.imooc.long5zb.config;

import com.imooc.long5zb.entity.User;
import com.imooc.long5zb.dao.UserRepository;
import com.imooc.long5zb.handler.MongoUserHandler;
import com.imooc.long5zb.handler.TimeHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;

import java.util.Collection;

import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
import static org.springframework.web.reactive.function.server.RequestPredicates.accept;
import static org.springframework.web.reactive.function.server.RouterFunctions.route;

@Configuration
public class RouterConfig {

    @Autowired
    private TimeHandler timeHandler;
    @Autowired
    private UserRepository userRepository;

    @Bean
    public RouterFunction<ServerResponse> timerRouter() {
        return route(GET("/time"), req -> timeHandler.getTime(req))
                .andRoute(GET("/date"), timeHandler :: getDate)
                .andRoute(GET("/times"), timeHandler :: sendTimePerSec);  // 这种方式相对于上一行更加简洁
    }

    @Bean
    public RouterFunction<ServerResponse> findAllUser() {
        return RouterFunctions.route(RequestPredicates.GET("/user/all"),
                request -> {
                    Collection<User> userList = userRepository.findAll();
                    Flux<User> userFlux = Flux.fromIterable(userList);
                    return ServerResponse.ok().body(userFlux, User.class);
                });
    }

    @Bean
    public RouterFunction<ServerResponse> mongoUserRoute(MongoUserHandler handler) {
        return RouterFunctions.nest(RequestPredicates.path("/mongo_user/route"),
                RouterFunctions.route(RequestPredicates.GET("/"), handler :: getAllUser)    //查询用户
                .andRoute(RequestPredicates.POST("/").and(accept(MediaType.APPLICATION_JSON_UTF8)), handler::createUser)    //创建用户
                .andRoute(RequestPredicates.DELETE("/{id}"), handler :: deleteUserById)
        );

    }


}
